package fun.hijklmn.magic.image.server.controller;

import com.google.common.collect.Lists;
import fun.hijklmn.magic.common.utils.ResultVOUtil;
import fun.hijklmn.magic.common.vo.req.PageVO;
import fun.hijklmn.magic.common.vo.resp.PageResultVO;
import fun.hijklmn.magic.common.vo.resp.ResultVO;
import fun.hijklmn.magic.image.common.pojo.Image;
import fun.hijklmn.magic.image.common.vo.req.ImageQueryReqVO;
import fun.hijklmn.magic.image.common.vo.resp.ImageQueryRespVO;
import fun.hijklmn.magic.image.server.config.ImageProperties;
import fun.hijklmn.magic.image.server.service.ImageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author gfs
 * @since 2021-04-28
 */
@Api(value = "图片管理", tags = "图片服务前端控制器")
@RestController
public class ImageController {

    @Autowired
    private ImageService imageService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ImageProperties imageProperties;

    @ApiOperation(value = "分页查询图片", tags = "图片服务前端控制器")
    @GetMapping("/page")
    public ResultVO<PageResultVO<ImageQueryRespVO>> page(ImageQueryReqVO imageQueryReqVO, PageVO pageVO) {

        PageResultVO<Image> pageResultVO = imageService.page(imageQueryReqVO, pageVO);

        List<ImageQueryRespVO> imageQueryRespVOList = Lists.newArrayList();

        pageResultVO.getItems().forEach(image -> {
            ImageQueryRespVO imageQueryRespVO = new ImageQueryRespVO();
            BeanUtils.copyProperties(image, imageQueryRespVO);
            imageQueryRespVOList.add(imageQueryRespVO);
        });

        return ResultVOUtil.success(new PageResultVO<ImageQueryRespVO>(pageVO, pageResultVO.getTotalNum(), imageQueryRespVOList));

    }

    @ApiOperation(value = "获取首页图片", tags = "图片服务前端控制器")
    @GetMapping("/getHotImage")
    public ResultVO<List<ImageQueryRespVO>> getHotImage() {

        List<Image> imageList = null;

        if (redisTemplate.hasKey(imageProperties.getHomeHotImageCache())) {
            imageList = (List<Image>) redisTemplate.opsForValue().get(imageProperties.getHomeHotImageCache());
        }

        List<ImageQueryRespVO> imageQueryRespVOList = Lists.newArrayList();

        imageList.forEach(image -> {
            ImageQueryRespVO imageQueryRespVO = new ImageQueryRespVO();
            BeanUtils.copyProperties(image, imageQueryRespVO);
            imageQueryRespVOList.add(imageQueryRespVO);
        });

        return ResultVOUtil.success(imageQueryRespVOList);

    }

}

